<script lang="ts" setup>
import type { TasksApi } from '#/api/spa/tasks';
import type { VxeTableInstance } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';
import { cloneDeep, formatDateTime } from '@vben/utils';
import {
  Button,
  message,
  Tabs,
  Pagination,
  Form,
  RangePicker,
  DatePicker,
  Select,
  Input,
} from 'ant-design-vue';
import { DictTag } from '#/components/dict-tag';
import TasksForm from './modules/form.vue';
import { Download, Plus, RefreshCw, Search, Trash2 } from '@vben/icons';
import { ContentWrap } from '#/components/content-wrap';
import { VxeColumn, VxeTable } from '#/adapter/vxe-table';
import { TableToolbar } from '#/components/table-toolbar';
import { useTableToolbar } from '#/hooks';

import { ref, h, reactive, onMounted, nextTick } from 'vue';
import { $t } from '#/locales';
import { isEmpty } from '@vben/utils';
import {
  getTasksPage,
  deleteTasks,
  deleteTasksList,
  exportTasks,
} from '#/api/spa/tasks';
import { downloadFileFromBlobPart } from '@vben/utils';

import { getRangePickerDefaultProps } from '#/utils';
const loading = ref(true); // 列表的加载中
const list = ref<TasksApi.Tasks[]>([]); // 列表的数据

const total = ref(0); // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  technicianId: undefined,
  projectName: undefined,
  status: undefined,
  roomNumber: undefined,
  duration: undefined,
  dispatchMethod: undefined,
  handCardId: undefined,
  startTime: undefined,
  endTime: undefined,
  actualDuration: undefined,
  createTime: undefined,
});
const queryFormRef = ref(); // 搜索的表单
const exportLoading = ref(false); // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = cloneDeep(queryParams) as any;
    if (params.startTime && Array.isArray(params.startTime)) {
      params.startTime = (params.startTime as string[]).join(',');
    }
    if (params.endTime && Array.isArray(params.endTime)) {
      params.endTime = (params.endTime as string[]).join(',');
    }
    if (params.createTime && Array.isArray(params.createTime)) {
      params.createTime = (params.createTime as string[]).join(',');
    }
    const data = await getTasksPage(params);
    list.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: TasksForm,
  destroyOnClose: true,
});

/** 创建任务派工 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑任务派工 */
function handleEdit(row: TasksApi.Tasks) {
  formModalApi.setData(row).open();
}

/** 删除任务派工 */
async function handleDelete(row: TasksApi.Tasks) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteTasks(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_process_msg',
    });
    await getList();
  } finally {
    hideLoading();
  }
}

/** 批量删除任务派工 */
async function handleDeleteBatch() {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting'),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteTasksList(checkedIds.value);
    checkedIds.value = [];
    message.success($t('ui.actionMessage.deleteSuccess'));
    await getList();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({ records }: { records: TasksApi.Tasks[] }) {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出表格 */
async function onExport() {
  try {
    exportLoading.value = true;
    const data = await exportTasks(queryParams);
    downloadFileFromBlobPart({ fileName: '任务派工.xls', source: data });
  } finally {
    exportLoading.value = false;
  }
}

/** 初始化 */
const { hiddenSearchBar, tableToolbarRef, tableRef } = useTableToolbar();
onMounted(() => {
  getList();
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="getList" />

    <ContentWrap v-if="!hiddenSearchBar">
      <!-- 搜索工作栏 -->
      <Form :model="queryParams" ref="queryFormRef" layout="inline">
        <Form.Item label="技师ID" name="technicianId">
          <Input
            v-model:value="queryParams.technicianId"
            placeholder="请输入技师ID"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="项目名称" name="projectName">
          <Input
            v-model:value="queryParams.projectName"
            placeholder="请输入项目名称"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="任务状态" name="status">
          <Select
            v-model:value="queryParams.status"
            placeholder="请选择任务状态"
            allowClear
            class="w-full"
          >
            <Select.Option label="请选择字典生成" value="" />
          </Select>
        </Form.Item>
        <Form.Item label="房间号" name="roomNumber">
          <Input
            v-model:value="queryParams.roomNumber"
            placeholder="请输入房间号"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="应钟时长" name="duration">
          <Input
            v-model:value="queryParams.duration"
            placeholder="请输入应钟时长"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="派工方式" name="dispatchMethod">
          <Input
            v-model:value="queryParams.dispatchMethod"
            placeholder="请输入派工方式"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="关联手牌ID" name="handCardId">
          <Input
            v-model:value="queryParams.handCardId"
            placeholder="请输入关联手牌ID"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="开始时间" name="startTime">
          <RangePicker
            v-model:value="queryParams.startTime"
            v-bind="getRangePickerDefaultProps()"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="结束时间" name="endTime">
          <RangePicker
            v-model:value="queryParams.endTime"
            v-bind="getRangePickerDefaultProps()"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="实际时长" name="actualDuration">
          <Input
            v-model:value="queryParams.actualDuration"
            placeholder="请输入实际时长"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="创建时间" name="createTime">
          <RangePicker
            v-model:value="queryParams.createTime"
            v-bind="getRangePickerDefaultProps()"
            class="w-full"
          />
        </Form.Item>
        <Form.Item>
          <Button class="ml-2" @click="resetQuery"> 重置 </Button>
          <Button class="ml-2" @click="handleQuery" type="primary">
            搜索
          </Button>
        </Form.Item>
      </Form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap title="任务派工">
      <template #extra>
        <TableToolbar
          ref="tableToolbarRef"
          v-model:hidden-search="hiddenSearchBar"
        >
          <Button
            class="ml-2"
            :icon="h(Plus)"
            type="primary"
            @click="handleCreate"
            v-access:code="['spa:tasks:create']"
          >
            {{ $t('ui.actionTitle.create', ['任务派工']) }}
          </Button>
          <Button
            :icon="h(Download)"
            type="primary"
            class="ml-2"
            :loading="exportLoading"
            @click="onExport"
            v-access:code="['spa:tasks:export']"
          >
            {{ $t('ui.actionTitle.export') }}
          </Button>
          <Button
            :icon="h(Trash2)"
            type="primary"
            danger
            class="ml-2"
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-access:code="['spa:tasks:delete']"
          >
            批量删除
          </Button>
        </TableToolbar>
      </template>
      <vxe-table
        ref="tableRef"
        :data="list"
        show-overflow
        :loading="loading"
        @checkboxAll="handleRowCheckboxChange"
        @checkboxChange="handleRowCheckboxChange"
      >
        <vxe-column type="checkbox" width="40"></vxe-column>
        <vxe-column field="id" title="主键ID" align="center" />
        <vxe-column field="technicianId" title="技师ID" align="center" />
        <vxe-column field="projectName" title="项目名称" align="center" />
        <vxe-column field="status" title="任务状态" align="center" />
        <vxe-column field="roomNumber" title="房间号" align="center" />
        <vxe-column field="duration" title="应钟时长" align="center" />
        <vxe-column field="dispatchMethod" title="派工方式" align="center" />
        <vxe-column field="handCardId" title="关联手牌ID" align="center" />
        <vxe-column field="startTime" title="开始时间" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </vxe-column>
        <vxe-column field="endTime" title="结束时间" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </vxe-column>
        <vxe-column field="actualDuration" title="实际时长" align="center" />
        <vxe-column field="createTime" title="创建时间" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </vxe-column>
        <vxe-column field="operation" title="操作" align="center">
          <template #default="{ row }">
            <Button
              size="small"
              type="link"
              @click="handleEdit(row as any)"
              v-access:code="['spa:tasks:update']"
            >
              {{ $t('ui.actionTitle.edit') }}
            </Button>
            <Button
              size="small"
              type="link"
              danger
              class="ml-2"
              @click="handleDelete(row as any)"
              v-access:code="['spa:tasks:delete']"
            >
              {{ $t('ui.actionTitle.delete') }}
            </Button>
          </template>
        </vxe-column>
      </vxe-table>
      <!-- 分页 -->
      <div class="mt-2 flex justify-end">
        <Pagination
          :total="total"
          v-model:current="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          show-size-changer
          @change="getList"
        />
      </div>
    </ContentWrap>
  </Page>
</template>
